package com.margo.project.socket;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.Socket;
public class CorsTask implements Runnable {

	private Socket socket;
	public CorsTask(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		InputStreamReader is = null;
		try {
			is = new InputStreamReader(socket.getInputStream(), "UTF-8");
			char[] c = new char[1024];
			StringBuffer sb = new StringBuffer();
			int index;
			while ((index = is.read(c)) != -1) {
				sb.append(new String(c, 0, index));
				// 阻塞了
				break;
			}
			System.out.println(sb.toString());
			Writer writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
			if (sb.toString().startsWith("OPTIONS")) {
				options(writer);
			} else {
				form(writer);
			}
			// 会报错

			// writer.flush();
			writer.close();
			is.close();
			socket.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	public void options(Writer writer) throws IOException {
		writer.write("HTTP/1.1 200\r\n");
		writer.write("Vary: Origin\r\n");
		writer.write("Vary: Access-Control-Request-Method\r\n");
		writer.write("Vary: Access-Control-Request-Headers\r\n");
		writer.write("Access-Control-Allow-Origin: http://localhost:8080\r\n");
		writer.write("Access-Control-Allow-Methods: POST\r\n");
		writer.write("Access-Control-Allow-Headers: sign,token,access-token,content-type\r\n");
		writer.write("Access-Control-Allow-Credentials: true\r\n");
		writer.write("Content-Length: 0\r\n");
		writer.write("Date: Sun, 13 Sep 2020 02:45:43 GMT\r\n");
		writer.write("\r\n");
		writer.close();

	}

	public void form(Writer writer) throws IOException {

		writer.write("HTTP/1.1 200\r\n");
		writer.write("Vary: Origin\r\n");
		writer.write("Vary: Access-Control-Request-Method\r\n");
		writer.write("Vary: Access-Control-Request-Headers\r\n");
		writer.write("Access-Control-Allow-Origin: http://localhost:8080\r\n");
		writer.write("Access-Control-Allow-Credentials: true\r\n");
		writer.write("Content-Type: application/json;charset=UTF-8\r\n");
		writer.write("Content-Length: 2\r\n");
		writer.write("Date: Sun, 13 Sep 2020 03:17:27 GMT\r\n");
		writer.write("\r\n");
		writer.write("ok\r\n");
		writer.write("\r\n");

	}

}
